import { useEffect, useState } from 'react';
import { Card, Table, Button, Modal, Form, Input, Select, message } from 'antd';
import { EyeOutlined, PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import API_CONFIG from '../utils/apiConfig';

const { Option } = Select;

const CameraPage = ({ user }) => {
  const [cameras, setCameras] = useState([]);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingCamera, setEditingCamera] = useState(null);
  // 修复前：组件开头的表单定义（保留这个）
  // 删除这个空的表单定义
  // const [form] = Form.useForm();
  
  // 正确的表单定义
  const [form] = Form.useForm();
  
  // 同时删除组件导出后的重复表单定义（第423行之后的那部分）

  // 获取相机列表
  const fetchCameras = async () => {
    setLoading(true);
    try {
      // 从后端API获取相机数据
      const response = await API_CONFIG.fetch('cameras');
      
      if (response.ok) {
        const data = await response.json();
        // 处理API返回的数据，确保字段名称匹配组件需求
        const formattedCameras = data.map(camera => ({
          id: camera.id,
          name: camera.point_name || '未知相机',
          //status: camera.status || 'offline',
          //location: camera.location || '',
          region: camera.region || '未知区域',
          recognitionModel: camera.recognition_model || '默认模型',
          //resolution: camera.resolution || '',
          //description: camera.description || '',
          monitorType: camera.monitor_type || '0',
          channelNumber: camera.channel_number || '',
          pointCode: camera.point_code || ''
        }));
        setCameras(formattedCameras);
        //message.success('相机列表获取成功');
      } else {
        // API调用失败时使用模拟数据作为降级方案
        console.log('API请求失败');
        /*
        const mockCameras = [
          {
            id: 1,
            name: '前门口摄像头',
            rtspUrl: 'rtsp://192.168.1.100:554/stream1',
            status: 'online',
            location: '前门',
            area: '办公区',
            recognitionModel: '人脸识别模型',
            resolution: '1080p',
            description: '监控前门进出情况'
          },
          {
            id: 2,
            name: '停车场摄像头',
            rtspUrl: 'rtsp://192.168.1.101:554/stream1',
            status: 'online',
            location: '停车场',
            area: '外部区域',
            recognitionModel: '车辆识别模型',
            resolution: '720p',
            description: '监控停车场车辆情况'
          },
          {
            id: 3,
            name: '仓库摄像头',
            rtspUrl: 'rtsp://192.168.1.102:554/stream1',
            status: 'offline',
            location: '仓库',
            area: '仓储区',
            recognitionModel: '物品识别模型',
            resolution: '1080p',
            description: '监控仓库内部情况'
          }
        ];*/
        setCameras(mockCameras);
      }
    } catch (error) {
      console.error('获取相机列表失败:', error);
      message.error('相机列表获取失败，请检查网络连接');
      // 网络错误时也使用模拟数据
      /*
      const mockCameras = [
        {
          id: 1,
          name: '前门口摄像头',
          rtspUrl: 'rtsp://192.168.1.100:554/stream1',
          status: 'online',
          location: '前门',
          area: '办公区',
          recognitionModel: '人脸识别模型',
          resolution: '1080p',
          description: '监控前门进出情况'
        },
        {
          id: 2,
          name: '停车场摄像头',
          rtspUrl: 'rtsp://192.168.1.101:554/stream1',
          status: 'online',
          location: '停车场',
          area: '外部区域',
          recognitionModel: '车辆识别模型',
          resolution: '720p',
          description: '监控停车场车辆情况'
        },
        {
          id: 3,
          name: '仓库摄像头',
          rtspUrl: 'rtsp://192.168.1.102:554/stream1',
          status: 'offline',
          location: '仓库',
          area: '仓储区',
          recognitionModel: '物品识别模型',
          resolution: '1080p',
          description: '监控仓库内部情况'
        }
      ];*/
      setCameras(mockCameras);
    } finally {
      setLoading(false);
    }
  };

  // 初始化时获取相机列表
  useEffect(() => {
    fetchCameras();
  }, []);

  // 打开添加/编辑相机的模态框
  const showModal = (camera = null) => {
    if (camera) {
      setEditingCamera(camera);
      form.setFieldsValue({
        name: camera.name,
        // rtspUrl: camera.rtspUrl,
        // status: camera.status,
        // location: camera.location,
        //resolution: camera.resolution,
        region: camera.region || '',
        recognitionModel: camera.recognitionModel || '',
        monitorType: camera.monitorType || '',
        channelNumber: camera.channelNumber || '',
        pointCode: camera.pointCode || ''
      });
    } else {
      setEditingCamera(null);
      form.resetFields();
    }
    setIsModalVisible(true);
  };

  // 关闭模态框
  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  // 保存相机信息
  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      
      // 构建相机数据对象，确保包含所有必填字段
      const cameraData = {
        point_name: values.name,
        channel_number: values.channelNumber,
        region: values.region,
        recognition_model: values.recognitionModel,
        monitor_type: values.monitorType,
        point_code: values.pointCode
      };
      
      if (editingCamera) {
        // 编辑现有相机
        const url = API_CONFIG.getURL('cameras') + `/${editingCamera.id}`;
        const response = await fetch(url, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(cameraData),
        });
      
        if (response.ok) {
          await fetchCameras(); // 刷新相机列表
          message.success('相机信息更新成功');
          setIsModalVisible(false);
          form.resetFields();
        } else {
          const errorData = await response.json();
          message.error(errorData.error || '相机信息更新失败');
        }
      } else {
        // 添加新相机
        const response = await API_CONFIG.fetch('cameras', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(cameraData),
        });
      
        if (response.ok) {
          await fetchCameras(); // 刷新相机列表
          message.success('相机添加成功');
          setIsModalVisible(false);
          form.resetFields();
        } else {
          const errorData = await response.json();
          message.error(errorData.error || '相机添加失败');
          console.log('创建相机失败详情:', errorData);
        }
      }
    } catch (error) {
      console.error('保存相机信息失败:', error);
      message.error('操作失败，请检查网络连接');
    }
  };

  // 删除相机
  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除此相机吗？删除后无法恢复。',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          const url = API_CONFIG.getURL('cameras') + `/${id}`;
          const response = await fetch(url, {
            method: 'DELETE',
          });
          
          if (response.ok) {
            await fetchCameras(); // 刷新相机列表
            message.success('相机删除成功');
          } else {
            const errorData = await response.json();
            message.error(errorData.error || '相机删除失败');
          }
        } catch (error) {
          console.error('删除相机失败:', error);
          message.error('删除失败，请检查网络连接');
        }
      }
    });
  };

  // 表格列配置
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80
    },
    {
      title: '相机名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true
    },
    {
      title: '区域',
      dataIndex: 'region',
      key: 'region'
    },
    {
      title: '识别模型',
      dataIndex: 'recognitionModel',
      key: 'recognitionModel'
    },
    {
      title: '监控类型',
      dataIndex: 'monitorType',
      key: 'monitorType'
    },
    {
      title: '通道号',
      dataIndex: 'channelNumber',
      key: 'channelNumber'
    },
    {
      title: '相机代码',
      dataIndex: 'pointCode',
      key: 'pointCode'
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <div style={{ display: 'flex', gap: '8px' }}>
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => showModal(record)}
            size="small"
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />} 
            onClick={() => handleDelete(record.id)}
            size="small"
          >
            删除
          </Button>
        </div>
      )
    }
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Card
        title={<div style={{ display: 'flex', alignItems: 'center' }}>
          <EyeOutlined style={{ marginRight: '8px' }} />
          相机管理
        </div>}
        extra={
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={() => showModal()}
          >
            添加相机
          </Button>
        }
        style={{ marginBottom: '24px' }}
      >
        <Table
          columns={columns}
          dataSource={cameras}
          rowKey="id"
          loading={loading}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 个相机`
          }}
          scroll={{ x: 'max-content' }}
        />
      </Card>

      {/* 添加/编辑相机的模态框 */}
      <Modal
        title={editingCamera ? '编辑相机' : '添加相机'}
        open={isModalVisible}
        onOk={handleSave}
        onCancel={handleCancel}
        okText="保存"
        cancelText="取消"
        width={700}
      >
        <Form
          form={form}
          layout="vertical"
          size="middle"
          style={{ marginTop: '16px' }}
        >
          <Form.Item
            label="相机名称"
            name="name"
            rules={[{ required: true, message: '请输入相机名称' }]}
          >
            <Input placeholder="请输入相机名称" />
          </Form.Item>

          <Form.Item
            label="区域"
            name="region"
            rules={[{ required: true, message: '请输入区域' }]}
          >
            <Input placeholder="请输入相机监控区域" />
          </Form.Item>

          <Form.Item
            label="识别模型"
            name="recognitionModel"
            rules={[{ required: true, message: '请输入识别模型' }]}
          >
            <Input placeholder="请输入识别模型" />
          </Form.Item>
          
          <Form.Item
            label="监控类型"
            name="monitorType"
            rules={[{ required: true, message: '请输入监控类型' }]}
          >
            <Input placeholder="请输入监控类型" />
          </Form.Item>
          
          <Form.Item
            label="通道号"
            name="channelNumber"
            rules={[{ required: true, message: '请输入通道号' }]}
          >
            <Input type="number" placeholder="请输入通道号" />
          </Form.Item>
          
          <Form.Item
            label="相机代码"
            name="pointCode"
            rules={[{ required: true, message: '请输入相机代码' }]}
          >
            <Input placeholder="请输入相机代码" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default CameraPage;

